{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Default value for requires_grad for x: False\n",
      "Updated  value for requires_grad for x: True\n",
      "Final value for Function f =  tensor([-3.], grad_fn=<MulBackward0>)\n",
      "Gradient value for x: tensor([3.])\n",
      "Gradient value for y: tensor([3.])\n",
      "Gradient value for z: tensor([-1.])\n"
     ]
    }
   ],
   "source": [
    "#Listing 4-1 – Implementing autograd in PyTorch\n",
    "\n",
    "\n",
    "#Import required libraries\n",
    "import torch\n",
    "\n",
    "#Define Tensors\n",
    "x = torch.Tensor([1])\n",
    "y = torch.Tensor([-2])\n",
    "z= torch.Tensor([3])\n",
    "\n",
    "print(\"Default value for requires_grad for x:\",x.requires_grad)\n",
    "\n",
    "#Set the keyword requires_grad as True (default is False)\n",
    "x.requires_grad=True\n",
    "y.requires_grad=True\n",
    "z.requires_grad=True\n",
    "\n",
    "print(\"Updated  value for requires_grad for x:\",x.requires_grad)\n",
    "\n",
    "#Compute a\n",
    "a = x + y\n",
    "\n",
    "#Finally define the function f\n",
    "f = z * a\n",
    "\n",
    "print(\"Final value for Function f = \",f)\n",
    "\n",
    "#Compute gradients\n",
    "f.backward()\n",
    "\n",
    "#Print the gradient value\n",
    "print(\"Gradient value for x:\",x.grad)\n",
    "print(\"Gradient value for y:\",y.grad)\n",
    "print(\"Gradient value for z:\",z.grad)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
